package com.mutouren.common.log.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;

import com.mutouren.common.log.ILoggerFactory;
import com.mutouren.common.log.Logger;

public class Log4jLoggerFactory implements ILoggerFactory {

	private ConcurrentMap<String, Logger> loggerMap;

	public Log4jLoggerFactory() {
		loggerMap = new ConcurrentHashMap<String, Logger>();
	}

	public Logger getLogger(String name) {
		Logger logger = loggerMap.get(name);
		if (logger != null) {
			return logger;
		} else {
			org.apache.log4j.Logger log4jLogger;
			if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
				log4jLogger = LogManager.getRootLogger();
			else
				log4jLogger = LogManager.getLogger(name);

			Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
			Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
			return oldInstance == null ? newInstance : oldInstance;
		}
	}
	
	/**
	 * 日志配置文件加载
	 * 如果 filePath="log4j.properties", 且在classpath路径下，不需配置
	 * 
	 * @param filePath
	 * @since
	 */
	public static void loadConfig(String filePath) {
		PropertyConfigurator.configure(filePath);
		// BasicConfigurator.configure();
	}

	@Override
	public void close() {
		LogManager.shutdown();		
	}
	
}
